<template>
  <div class="machine-detail full-height flex" v-if="isRefresh">
    <template v-if="fromList">
      <machine-detail-box ref="details" :fromList="true" :operatorName="operatorName" :technicianName="technicianName" :currentStop="currentStop" @changeStatus="changeStatus"/>
      <div class="flex-1 full-height bg-white border" style="margin-left: 24px;">
        <q-tabs
          v-model="tab"
          shrink stretch dense
          inline-label
          align="left"
          active-color="primary"
          indicator-color="primary"
          style="padding: 10px 20px 0;
           position: relative"
        >
          <q-tab name="process" v-if="!showPlc" label="实时" icon="iconfont icontubiao-125"
                 v-stat="{id:CommonConfig.statData.machine.process.id,name:CommonConfig.statData.machine.process.id}"/>
          <q-tab name="timeline" label="时间线" icon="iconfont icontubiao-112"
                 v-stat="{id:CommonConfig.statData.machine.timeline.id,name:CommonConfig.statData.machine.timeline.id}"/>
          <q-tab name="monitor" v-if="showCamera" label="视频监控" icon="iconfont icontubiao-15"/>
          <q-tab name="availability" label="时间开动率" icon="iconfont icontubiao2-80"/>
          <q-tab name="plc" v-if="showPlc" label="实时数据" icon="iconfont icontubiao-112"/>
          <q-tab name="historyData" v-if="showPlc" label="设备历史数据" icon="iconfont icontubiao-112"/>
        </q-tabs>
        <q-separator class="line margin-l-20 margin-r-20" style="width: calc(100% - 40px)"/>
        <q-tab-panels v-model="tab" animated style="height: calc(100% - 67px)" class="scrollbar">
          <q-tab-panel name="process" style="padding:0" class="full-height">
            <online-process
              class="full-height"
              :processData="processData"
              ref="onlineProcessTab"
            />
          </q-tab-panel>
          <q-tab-panel name="timeline" style="padding:0" class="full-height">
            <time-line ref="timeline" style="padding: 20px 0" class="full-height" :msg="timeLineMessage" :details="details" :fromList="true"></time-line>
          </q-tab-panel>
          <q-tab-panel v-if="showCamera" name="monitor" style="padding:0" class="full-height">
            <monitor ref="monitor" :ip="processData.caremaIp" style="padding: 20px" class="full-height"></monitor>
          </q-tab-panel>
          <q-tab-panel name="availability" style="padding:0" class="full-height">
            <availability ref="availability" style="padding:0" class="full-height" :id="id"></availability>
          </q-tab-panel>
          <q-tab-panel name="plc" style="padding:0" class="full-height">
            <PLC :processData="processData"/>
          </q-tab-panel>
          <q-tab-panel name="historyData" style="padding:0" class="full-height">
            <history-data :processData="processData" :selTab="tab"/>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </template>
    <template v-else>
      <machine-detail-box ref="details" :fromList="false"></machine-detail-box>
      <div class="flex-1 full-height bg-white border" style="margin-left: 24px;">
        <time-line ref="timeLine" style="padding: 20px 0" class="full-height" :msg="timeLineMessage" :details="details" ></time-line>
      </div>
    </template>
    <CurrentShutdownDialog ref="currentShutdownDialog" :id="id" @setSuccess="getCurrentStopCauseData(id)"/>
  </div>
</template>

<script>
import machineDetailBox from './components/machine-detail-box'
import CurrentShutdownDialog from './components/current-shutdown-dialog'
import OnlineProcess from './online-process'
import TimeLine from './time-line'
import Monitor from './monitor'
import Availability from './availability'
import PLC from './PLC'
import HistoryData from './history-data'
import { mapActions, mapGetters, mapMutations } from 'vuex'
import { getCurrentStopCause, getMachineDetails, isUnBind } from '../../boot/status-monitor/machine'
import { getStatusMonitorList, setStatusMonitorList } from '../../assets/js/storage'
export default {
  name: 'status-machine-detail',
  components: {
    machineDetailBox,
    OnlineProcess,
    TimeLine,
    Monitor,
    Availability,
    CurrentShutdownDialog,
    PLC,
    HistoryData
  },
  data () {
    return {
      isRefresh: true,
      id: null,
      fromList: false,
      deviceInfo: null, // 设备信息
      tab: getStatusMonitorList() || 'process', // process / timeline / monitor / availability
      details: {
        boxId: '',
        id: ''
      }, // 传给子组件机床详情的数据，用于填充显示项
      timeLineMessage: '', // 时间线msg
      params: {},
      processData: {},
      currentStop: null,
      operatorName: '',
      technicianName: '',
      showPlc: false
    }
  },
  watch: {
    tab (val) {
      // 当为plc时候不缓存tab
      if (val === 'plc') return
      setStatusMonitorList(val)
    },
    // 如果显示plc的话，就把tab页面设置为plc
    showPlc (val) {
      if (val) {
        this.tab = 'plc'
      }
    },
    'params.status': {
      handler (val) {
        if (this.$route.name === 'statusMachineDetail' && val + '' === this.Enums.MACHINES_STATUS.HALTING.value + '' && !this.currentStop && this.id) {
          this.$refs.currentShutdownDialog.showDialog(this.params.oldSecond)
        } else {
          this.$refs.currentShutdownDialog.hideDialog()
        }
      }
    }
  },
  // mounted () {
  //   this.params = null
  //   this.initParams()
  //   this.$refs.details.getDetails(this.params)
  // },
  computed: {
    ...mapGetters(['client', 'footprint', 'isUnbound']),
    showCamera () {
      return !!this.processData.caremaIp
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.saveCustomerSet()
      if (vm.$route.query.id) {
        vm.showPlc = vm.$route.query.isPlc + '' === '1'
        vm.params = null
        vm.getCurrentStopCauseData(vm.$route.query.id).then(() => {
          vm.initParams()
          vm.$refs.details.getDetails(vm.params)
        })
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    this.$refs.details.closeUbscribeTopic()
    this.client.unsubscribe('boxTypeTopic')
    next()
  },
  methods: {
    ...mapActions([
      'saveCustomerSet'
    ]),
    getCurrentStopCauseData (id) {
      return new Promise(resolve => {
        getCurrentStopCause(id).then(res => {
          if (res.data) {
            this.currentStop = res.data
          } else {
            this.currentStop = null
          }
          resolve()
        })
      })
    },
    // 订阅关于盒子解绑的消息
    //
    onSubscribe (deviceId) {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.boxTypeTopic.subscribeTopic}${deviceId}`, this.getBoxType, { id: `boxTypeTopic` }
        )
      }
    },
    // 获取盒子相关信息
    getBoxType (res) {
      const member = JSON.parse(res.body).data
      if (member.isUnbound && member.deviceId === this.params.deviceId) {
        this.$refs.onlineProcessTab && clearInterval(this.$refs.onlineProcessTab.timerSend)
        this.$refs.onlineProcessTab && clearInterval(this.$refs.onlineProcessTab.timerTime)
        this.client.unsubscribe('boxTypeTopic')
        if (!this.$route.fullPath.includes('machine-detail')) return
        this.closeBox()
      }
    },
    closeBox () {
      this.$refs.onlineProcessTab && clearInterval(this.$refs.onlineProcessTab.timerSend)
      this.$refs.onlineProcessTab && clearInterval(this.$refs.onlineProcessTab.timerTime)
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>盒子已被解绑，请刷新界面</p>`,
        persistent: true,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      }).onOk(() => {
        this.$router.push('/main/status-monitor-v3/machine-list')
        const footprint = this.footprint.filter(v => !v.link.includes('machine-detail'))
        this.set_footprint(footprint)
      })
    },
    // 获取详情
    getDetails () {
      getMachineDetails(this.details.id).then(res => {
        this.params = {
          ...this.params,
          oldSecond: res.data.statusDuration,
          ...res.data
        }
        this.processData = { ...this.params }
        if (this.processData.isPlc !== 1 && (this.tab === 'plc' || this.tab === 'historyData')) {
          this.tab = 'process'
        }
      }).then(() => {
        this.params.deviceId && this.onSubscribe(this.params.deviceId)
        this.$refs.details.getDetails(this.params)
      })
    },
    // 初始化路由参数
    initParams () {
      const params = this.$route.query
      this.operatorName = params.operatorName
      this.technicianName = params.technicianName
      this.params = params
      this.fromList = params.fromList || false
      this.details = {
        boxId: params.boxId,
        id: params.id
      }
      this.id = params.id
      this.deviceInfo = params.deviceInfo
      isUnBind(this.params.id).then(res => {
        if (!res.data) {
          this.closeBox()
        } else {
          this.getDetails()
        }
      })
      if (!this.fromList) {
        this.tab = 'timeline'
        this.details['date'] = params.date
        this.$nextTick(() => {
          this.$refs.timeLine.changeData(this.details)
        })
      }
    },
    changeStatus () {
      this.currentStop = null
      if (this.$route.name === 'statusMachineDetail' && this.params.status + '' === this.Enums.MACHINES_STATUS.HALTING.value + '' && this.id) {
        this.$refs.currentShutdownDialog.showDialog(this.params.oldSecond)
      }
    },
    ...mapMutations({
      'set_footprint': 'SET_FOOTPRINT'
    })
  }
}
</script>

<style scoped lang="scss">
  .border{
    border-radius: 6px;
    overflow: hidden
  }
  /deep/ {
    .q-panel::-webkit-scrollbar {
      width: 8px;
      height: 8px;
      background-color: transparent;
    }
    .q-panel::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background-color: rgba(95, 119, 253, 0);
      transition: background-color 500ms ease-in;
    }
    .q-panel:hover::-webkit-scrollbar-thumb {
      background-color: rgba(95, 119, 253, .5);
    }
  }
</style>
